package cn.ciis.basic.kit;

import cn.ciis.basic.interceptor.AuthCacheClearInterceptor;
import cn.ciis.basic.model.Account;
import cn.ciis.sys.login.LoginService;
import com.jfinal.aop.Aop;
import com.jfinal.plugin.druid.DruidStatViewHandler;
import com.jfinal.plugin.druid.IDruidStatViewAuth;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class DruidKit {

  static LoginService loginSrv = Aop.get(LoginService.class);

  public static DruidStatViewHandler getDruidStatViewHandler() {
    return new DruidStatViewHandler(
        "/assets/druid",
        new IDruidStatViewAuth() {
          @Override
          public boolean isPermitted(HttpServletRequest request) {
            String sessionId = DruidKit.getCookie(request, LoginService.SESSION_ID_NAME);
            if (sessionId != null) {
              Account loginAccount = DruidKit.loginSrv.getLoginAccountWithSessionId(sessionId);
              return AuthCacheClearInterceptor.isAdmin(loginAccount);
            }
            return false;
          }
        });
  }

  public static String getCookie(HttpServletRequest request, String name) {
    Cookie cookie = getCookieObject(request, name);
    return cookie != null ? cookie.getValue() : null;
  }

  private static Cookie getCookieObject(HttpServletRequest request, String name) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (cookie.getName().equals(name)) {
          return cookie;
        }
      }
    }
    return null;
  }
}
